<template>
  <div>
    <ListTable ref="RefListTable" :table-data="tableData" :table-col="tableCol" />
  </div>
</template>
<script>
import { parseTime } from '@/utils'
import listMixin from '@/mixins/list'
// import ListFilter from '@/components/ListFilter'
import { mapGetters } from 'vuex'
import { realtimeLocation } from '@/api/api'
export default {
  // components: {
  // ListFilter
  // },
  mixins: [listMixin],
  data() {
    return {
      timeId: '',
      isTimer: false,
      listTitle: [
        'carId',
        'car.carType',
        'car.RFID',
        'car.plateNumber',
        'baseStation.area.name',
        'autoGate.area.name',
        'autoGate.name',
        'enterTime',
        'updateTime'
      ],
      // 列表数据
      tableData: [],
      // 列表表头
      tableCol: [
        { type: 'index', label: '序号', width: '60px', height: '250' },
        {
          label: '车辆类型',
          formatter(row, col, cell) {
            let deptName = ''
            if (row.carId) {
              deptName = row.car.carType
            }
            return deptName || ''
          },
          minWidth: '142px'
        },
        {
          label: 'RFID',
          formatter(row, col, cell) {
            let rfid = ''
            if (row.carId) {
              rfid = row.car.rfid
            }
            return rfid || ''
          }
        },
        {
          label: '车牌',
          formatter(row, col, cell) {
            let number = ''
            if (row.carId) {
              number = row.car.plateNumber
            }
            return number || ''
          },
          minWidth: '116px'
        },
        {
          label: '所在位置',
          formatter(row, col, cell) {
            return row.baseStation ? row.baseStation.area.name : row.autoGate.name
          }
        },
        {
          label: '进场时间',
          formatter(row, col, cell) {
            return parseTime(new Date(row.enterTime).getTime(), '{y}-{m}-{d} {h}:{i}')
          },
          minWidth: '162px'
        },
        {
          label: '更新时间',
          formatter(row, col, cell) {
            return parseTime(new Date(row.updateTime).getTime(), '{y}-{m}-{d} {h}:{i}')
          },
          minWidth: '162px'
        },
        {
          label: '本次进场时长',
          formatter(row, col, cell) {
            const date1 = new Date() // 开始时间
            const date2 = new Date(row.enterTime) // 结束时间
            const date3 = date1.getTime() - new Date(date2).getTime() // 时间差的毫秒数

            // 计算出相差天数
            const days = Math.floor(date3 / (24 * 3600 * 1000))

            // 计算出小时数
            const leave1 = date3 % (24 * 3600 * 1000) // 计算天数后剩余的毫秒数
            const hours = Math.floor(leave1 / (3600 * 1000))

            // 计算相差分钟数
            const leave2 = leave1 % (3600 * 1000) // 计算小时数后剩余的毫秒数
            const minutes = Math.floor(leave2 / (60 * 1000))

            return (days ? days + '天 ' : '') + hours + '小时 ' + minutes + '分钟'
          },
          minWidth: '161px'
        }
        // { label: '操作', custom: 'col1', minWidth: '126px' }
      ]
    }
  },
  computed: {
    ...mapGetters(['gateSwaitch'])
  },
  mounted() {
    var that = this
    // 定时更新列表
    this.timeId = setInterval(() => {
      that.isTimer = true
      const data = JSON.parse(localStorage.getItem('serchData'))
      // 有值调用查询
      this.getList(data)
    }, 1000 * 5)
  },
  beforeDestroy() {
    clearInterval(this.timeId)
  },
  methods: {
    // 请求列表数据
    async getList(query) {
      if (this.isTimer === false) {
        this.tableLoading = true
      }
      try {
        const obj = query || { pageIndex: 1, pageSize: 10, orderBy: 'updatedTime', orderByAscent: false, search: [] }
        obj.orderBy = 'updatedTime'
        obj.orderByAscent = false
        // 如果没有search，添加一个，以免报错
        if (!obj.search) {
          obj.search = []
        }
        if (this.gateSwaitch === '不展示') {
          if (obj.search.length === 0) {
            obj.search = [
              {
                key: 'autoGateId',
                value: 2,
                operation: 0
              }
            ]
          } else {
            if (!obj.search.some(r => r.key === 'autoGateId')) {
              obj.search.push({
                key: 'autoGateId',
                value: 2,
                operation: 0
              })
            }
          }
        } else {
          if (obj.search.length === 0) {
            obj.search = []
          } else {
            const i = query.search.findIndex(item => {
              return item.key === 'autoGateId'
            })
            if (i > -1) {
              query.search.splice(i, 1)
            }
          }
        }
        // 如果不展示闸机数据，需设置值为null
        obj.search.forEach((edit, index) => {
          if (edit.key === 'autoGateId' && edit.value === 2) {
            edit.value = null
          } else if (edit.key === 'baseStation.area.id' && edit.value === '空') {
            edit.value = null
          }
        })
        // 添加人员为空
        if (!obj.search.some(r => r.key === 'EmployeeId')) {
          obj.search.push({
            key: 'EmployeeId',
            value: null,
            Operation: 0,
            relationship: 0,
            sequence: 0
          })
        }
        // 删除车辆为空
        var find = obj.search.find(r => r.key === 'CarId')
        if (find) {
          obj.search.splice(obj.search.indexOf(find), 1)
        }
        // 如果展示闸机数据，删除这个查询条件
        const findOne = obj.search.find(k => k.key === 'autoGateId' && k.value === 1)
        if (findOne) {
          obj.search.splice(obj.search.indexOf(findOne), 1)
        }
        obj.select = this.listTitle
        // 保存查询数据
        localStorage.setItem('serchData', JSON.stringify(obj))
        // 查询
        const {
          data: { items: resData, count, pageIndex }
        } = await realtimeLocation('post', obj, false)

        this.$nextTick(() => {
          this.tableData = []
          resData.forEach(item => {
            item.loadingEdit = false
            item.loadingDel = false
            // if (item.employeeId) {
            //   this.tableData.push(item)
            // }
          })
          this.tableData = JSON.parse(JSON.stringify(resData))
          this.$refs['RefListTable'].update({ page: pageIndex, count })
          this.tableLoading = false
        })
      } catch (err) {
        this.tableLoading = false
      }
    }
  }
}
</script>
